{% extends 'base.html' %}

{% block title %}{{ coach.real_name }} - 教练档案 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}教练档案{% endblock %}

{% block extra_css %}
<style>
    .profile-container {
        max-width: 1000px;
        margin: 0 auto;
        display: grid;
        grid-template-columns: 350px 1fr;
        gap: 2rem;
    }

    .profile-sidebar {
        display: grid;
        gap: 1.5rem;
    }

    .profile-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        position: sticky;
        top: 2rem;
    }

    .coach-avatar-section {
        text-align: center;
        margin-bottom: 2rem;
    }

    .coach-avatar-large {
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem;
        overflow: hidden;
        border: 4px solid #e9ecef;
        position: relative;
    }

    .coach-avatar-large img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .coach-avatar-large i {
        font-size: 4rem;
        color: #6c757d;
    }

    .avatar-upload-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.6);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        opacity: 0;
        transition: opacity 0.3s ease;
        cursor: pointer;
    }

    .coach-avatar-large:hover .avatar-upload-overlay {
        opacity: 1;
    }

    .coach-name-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }

    .coach-level-badge {
        display: inline-block;
        padding: 0.5rem 1rem;
        border-radius: 25px;
        font-weight: 600;
        font-size: 0.875rem;
        margin-bottom: 1rem;
    }

    .level-senior {
        background: #e7f3ff;
        color: #0056b3;
    }

    .level-middle {
        background: #fff3cd;
        color: #856404;
    }

    .level-junior {
        background: #d4edda;
        color: #155724;
    }

    .quick-info {
        display: grid;
        gap: 0.75rem;
    }

    .quick-info-item {
        display: flex;
        align-items: center;
        padding: 0.75rem;
        background: #f8f9fa;
        border-radius: 8px;
    }

    .quick-info-item i {
        width: 20px;
        margin-right: 0.75rem;
        color: #007bff;
    }

    .quick-info-item .label {
        font-weight: 600;
        color: #495057;
        min-width: 60px;
        margin-right: 1rem;
    }

    .quick-info-item .value {
        color: #6c757d;
        flex: 1;
    }

    .stats-mini {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
        margin-top: 1.5rem;
    }

    .stat-mini {
        text-align: center;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
    }

    .stat-mini-number {
        font-size: 1.25rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
    }

    .stat-mini-label {
        font-size: 0.75rem;
        color: #6c757d;
        margin-top: 0.25rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .profile-content {
        display: grid;
        gap: 2rem;
    }

    .content-section {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .section-header {
        display: flex;
        justify-content: between;
        align-items: center;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #f8f9fa;
    }

    .section-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 0.75rem;
        color: #007bff;
    }

    .edit-toggle {
        margin-left: auto;
    }

    .btn-edit-toggle {
        padding: 0.5rem 1rem;
        border-radius: 6px;
        font-size: 0.875rem;
        border: none;
        transition: all 0.2s ease;
    }

    .profile-form {
        display: none;
    }

    .profile-form.active {
        display: block;
    }

    .profile-display {
        display: block;
    }

    .profile-display.hidden {
        display: none;
    }

    .bio-text, .experience-text {
        line-height: 1.6;
        color: #495057;
        white-space: pre-wrap;
    }

    .empty-content {
        text-align: center;
        color: #6c757d;
        font-style: italic;
        padding: 2rem;
    }

    .form-group {
        margin-bottom: 1.5rem;
    }

    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
    }

    .form-control {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 0.75rem 1rem;
        transition: all 0.3s ease;
    }

    .form-control:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 1.5rem;
    }

    .performance-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .performance-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border-left: 4px solid;
        transition: all 0.3s ease;
    }

    .performance-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }

    .performance-card.students { border-left-color: #007bff; }
    .performance-card.revenue { border-left-color: #28a745; }
    .performance-card.hours { border-left-color: #17a2b8; }
    .performance-card.rating { border-left-color: #ffc107; }

    .performance-icon {
        font-size: 2rem;
        margin-bottom: 1rem;
    }

    .performance-icon.students { color: #007bff; }
    .performance-icon.revenue { color: #28a745; }
    .performance-icon.hours { color: #17a2b8; }
    .performance-icon.rating { color: #ffc107; }

    .performance-number {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
    }

    .performance-label {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.5rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .performance-sublabel {
        color: #6c757d;
        font-size: 0.75rem;
        margin-top: 0.25rem;
    }

    .photo-upload-area {
        position: relative;
        display: inline-block;
    }

    .photo-upload-input {
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }

    @media (max-width: 992px) {
        .profile-container {
            grid-template-columns: 1fr;
            gap: 1.5rem;
        }

        .profile-card {
            position: static;
        }

        .performance-stats {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 576px) {
        .profile-container {
            margin: 1rem;
        }

        .performance-stats {
            grid-template-columns: 1fr;
        }

        .stats-mini {
            grid-template-columns: 1fr;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="profile-container">
        <!-- 侧边栏档案卡片 -->
        <div class="profile-sidebar">
            <div class="profile-card">
                <div class="coach-avatar-section">
                    <div class="coach-avatar-large">
                        {% if coach.photo_url %}
                        <img src="{{ coach.photo_url }}" alt="{{ coach.real_name }}" id="avatarImage">
                        {% else %}
                        <i class="bi bi-person-circle" id="avatarPlaceholder"></i>
                        {% endif %}

                        {% if can_edit %}
                        <div class="avatar-upload-overlay">
                            <i class="bi bi-camera"></i>
                        </div>
                        <input type="file" class="photo-upload-input" accept="image/*" id="photoUpload">
                        {% endif %}
                    </div>

                    <h2 class="coach-name-title">{{ coach.real_name }}</h2>

                    {% if coach.coach_level %}
                    <span class="coach-level-badge level-{{ coach.coach_level }}">
                        {% if coach.coach_level == 'senior' %}高级教练
                        {% elif coach.coach_level == 'middle' %}中级教练
                        {% elif coach.coach_level == 'junior' %}初级教练
                        {% endif %}
                    </span>
                    {% endif %}
                </div>

                <div class="quick-info">
                    <div class="quick-info-item">
                        <i class="bi bi-telephone"></i>
                        <span class="label">手机：</span>
                        <span class="value">{{ coach.phone }}</span>
                    </div>

                    {% if coach.email %}
                    <div class="quick-info-item">
                        <i class="bi bi-envelope"></i>
                        <span class="label">邮箱：</span>
                        <span class="value">{{ coach.email }}</span>
                    </div>
                    {% endif %}

                    <div class="quick-info-item">
                        <i class="bi bi-geo-alt"></i>
                        <span class="label">校区：</span>
                        <span class="value">{{ coach.campus.name if coach.campus else '未分配' }}</span>
                    </div>

                    {% if coach.hourly_rate %}
                    <div class="quick-info-item">
                        <i class="bi bi-currency-yen"></i>
                        <span class="label">费用：</span>
                        <span class="value">{{ coach.hourly_rate }}元/小时</span>
                    </div>
                    {% endif %}

                    <div class="quick-info-item">
                        <i class="bi bi-flag"></i>
                        <span class="label">状态：</span>
                        <span class="value">
                            {% if coach.status == 'active' %}在职
                            {% elif coach.status == 'pending' %}待审核
                            {% elif coach.status == 'inactive' %}离职
                            {% endif %}
                        </span>
                    </div>

                    <div class="quick-info-item">
                        <i class="bi bi-calendar"></i>
                        <span class="label">注册：</span>
                        <span class="value">{{ coach.created_at.strftime('%Y年%m月') if coach.created_at else '未知' }}</span>
                    </div>
                </div>

                {% if statistics %}
                <div class="stats-mini">
                    <div class="stat-mini">
                        <div class="stat-mini-number">{{ statistics.total_students }}</div>
                        <div class="stat-mini-label">指导学员</div>
                    </div>
                    <div class="stat-mini">
                        <div class="stat-mini-number">{{ statistics.total_hours }}</div>
                        <div class="stat-mini-label">累计课时</div>
                    </div>
                    <div class="stat-mini">
                        <div class="stat-mini-number">{{ statistics.month_revenue }}</div>
                        <div class="stat-mini-label">本月收入</div>
                    </div>
                    <div class="stat-mini">
                        <div class="stat-mini-number">{{ statistics.avg_rating }}</div>
                        <div class="stat-mini-label">平均评分</div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="profile-content">
            <!-- 教学表现统计 -->
            {% if statistics %}
            <div class="content-section">
                <div class="section-header">
                    <h3 class="section-title">
                        <i class="bi bi-graph-up"></i>教学表现
                    </h3>
                </div>

                <div class="performance-stats">
                    <div class="performance-card students">
                        <div class="performance-icon students">
                            <i class="bi bi-people"></i>
                        </div>
                        <h4 class="performance-number">{{ statistics.total_students }}</h4>
                        <div class="performance-label">指导学员</div>
                        {% if statistics.pending_students > 0 %}
                        <div class="performance-sublabel">待审核：{{ statistics.pending_students }}人</div>
                        {% endif %}
                    </div>

                    <div class="performance-card revenue">
                        <div class="performance-icon revenue">
                            <i class="bi bi-currency-yen"></i>
                        </div>
                        <h4 class="performance-number">{{ statistics.month_revenue }}</h4>
                        <div class="performance-label">本月收入（元）</div>
                        <div class="performance-sublabel">本周：{{ statistics.week_revenue }}元</div>
                    </div>

                    <div class="performance-card hours">
                        <div class="performance-icon hours">
                            <i class="bi bi-clock"></i>
                        </div>
                        <h4 class="performance-number">{{ statistics.total_hours }}</h4>
                        <div class="performance-label">累计课时</div>
                        <div class="performance-sublabel">本月：{{ statistics.month_reservations }}节课</div>
                    </div>

                    <div class="performance-card rating">
                        <div class="performance-icon rating">
                            <i class="bi bi-star-fill"></i>
                        </div>
                        <h4 class="performance-number">{{ statistics.avg_rating }}</h4>
                        <div class="performance-label">平均评分</div>
                        <div class="performance-sublabel">{{ statistics.total_reviews }}条评价</div>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- 个人简介 -->
            <div class="content-section">
                <div class="section-header">
                    <h3 class="section-title">
                        <i class="bi bi-person-lines-fill"></i>个人简介
                    </h3>
                    {% if can_edit %}
                    <div class="edit-toggle">
                        <button type="button" class="btn btn-outline-primary btn-edit-toggle" onclick="toggleEdit('bio')">
                            <i class="bi bi-pencil me-1"></i>编辑
                        </button>
                    </div>
                    {% endif %}
                </div>

                <div class="profile-display" id="bioDisplay">
                    {% if coach.bio %}
                    <div class="bio-text">{{ coach.bio }}</div>
                    {% else %}
                    <div class="empty-content">
                        <i class="bi bi-file-text" style="font-size: 2rem; opacity: 0.5;"></i>
                        <p>暂无个人简介</p>
                        {% if can_edit %}
                        <p><small class="text-muted">点击编辑按钮添加个人简介</small></p>
                        {% endif %}
                    </div>
                    {% endif %}
                </div>

                {% if can_edit and form %}
                <div class="profile-form" id="bioForm">
                    <div class="form-group">
                        {{ form.bio.label(class="form-label") }}
                        {{ form.bio(class="form-control", id="bioInput") }}
                        <div class="form-text">介绍您的教学理念、专长特色等（最多500字）</div>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="cancelEdit('bio')">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveField('bio')">保存</button>
                    </div>
                </div>
                {% endif %}
            </div>

            <!-- 教学经验 -->
            <div class="content-section">
                <div class="section-header">
                    <h3 class="section-title">
                        <i class="bi bi-award"></i>教学经验
                    </h3>
                    {% if can_edit %}
                    <div class="edit-toggle">
                        <button type="button" class="btn btn-outline-primary btn-edit-toggle" onclick="toggleEdit('experience')">
                            <i class="bi bi-pencil me-1"></i>编辑
                        </button>
                    </div>
                    {% endif %}
                </div>

                <div class="profile-display" id="experienceDisplay">
                    {% if coach.experience %}
                    <div class="experience-text">{{ coach.experience }}</div>
                    {% else %}
                    <div class="empty-content">
                        <i class="bi bi-award" style="font-size: 2rem; opacity: 0.5;"></i>
                        <p>暂无教学经验描述</p>
                        {% if can_edit %}
                        <p><small class="text-muted">点击编辑按钮添加教学经验</small></p>
                        {% endif %}
                    </div>
                    {% endif %}
                </div>

                {% if can_edit and form %}
                <div class="profile-form" id="experienceForm">
                    <div class="form-group">
                        {{ form.experience.label(class="form-label") }}
                        {{ form.experience(class="form-control", id="experienceInput") }}
                        <div class="form-text">详细描述您的教学经验、获得的荣誉、专业资质等（最多1000字）</div>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="cancelEdit('experience')">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveField('experience')">保存</button>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 编辑模式切换
    window.toggleEdit = function(field) {
        const display = document.getElementById(`${field}Display`);
        const form = document.getElementById(`${field}Form`);
        const input = document.getElementById(`${field}Input`);

        if (display && form && input) {
            display.classList.add('hidden');
            form.classList.add('active');

            // 设置当前值
            {% if can_edit %}
            if (field === 'bio') {
                input.value = `{{ coach.bio or '' }}`;
            } else if (field === 'experience') {
                input.value = `{{ coach.experience or '' }}`;
            }
            {% endif %}

            input.focus();
        }
    };

    // 取消编辑
    window.cancelEdit = function(field) {
        const display = document.getElementById(`${field}Display`);
        const form = document.getElementById(`${field}Form`);

        if (display && form) {
            display.classList.remove('hidden');
            form.classList.remove('active');
        }
    };

    // 保存字段
    window.saveField = function(field) {
        const input = document.getElementById(`${field}Input`);
        const value = input.value.trim();

        // 创建FormData
        const formData = new FormData();
        formData.append(field, value);
        formData.append('csrf_token', '{{ csrf_token() }}');

        // 发送AJAX请求
        fetch('{{ url_for("coaches.profile", id=coach.id) }}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新显示
                updateFieldDisplay(field, value);
                cancelEdit(field);

                // 显示成功消息
                showMessage('保存成功！', 'success');
            } else {
                showMessage(data.error || '保存失败', 'error');
            }
        })
        .catch(error => {
            showMessage('网络错误，请重试', 'error');
            console.error('Error:', error);
        });
    };

    // 更新字段显示
    function updateFieldDisplay(field, value) {
        const display = document.getElementById(`${field}Display`);
        if (display) {
            if (value) {
                display.innerHTML = `<div class="${field}-text">${value}</div>`;
            } else {
                const emptyIcon = field === 'bio' ? 'file-text' : 'award';
                const emptyText = field === 'bio' ? '暂无个人简介' : '暂无教学经验描述';
                display.innerHTML = `
                    <div class="empty-content">
                        <i class="bi bi-${emptyIcon}" style="font-size: 2rem; opacity: 0.5;"></i>
                        <p>${emptyText}</p>
                        {% if can_edit %}
                        <p><small class="text-muted">点击编辑按钮添加${field === 'bio' ? '个人简介' : '教学经验'}</small></p>
                        {% endif %}
                    </div>
                `;
            }
        }
    }

    // 显示消息
    function showMessage(message, type) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;

        const container = document.querySelector('.container-fluid');
        container.insertAdjacentHTML('afterbegin', alertHtml);

        // 3秒后自动隐藏
        setTimeout(() => {
            const alert = container.querySelector('.alert');
            if (alert) {
                alert.remove();
            }
        }, 3000);
    }

    {% if can_edit %}
    // 头像上传处理
    const photoUpload = document.getElementById('photoUpload');
    const avatarImage = document.getElementById('avatarImage');
    const avatarPlaceholder = document.getElementById('avatarPlaceholder');

    if (photoUpload) {
        photoUpload.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // 检查文件类型
                if (!file.type.startsWith('image/')) {
                    showMessage('请选择图片文件', 'error');
                    return;
                }

                // 检查文件大小（5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showMessage('图片文件不能超过5MB', 'error');
                    return;
                }

                // 上传头像
                const formData = new FormData();
                formData.append('photo', file);
                formData.append('csrf_token', '{{ csrf_token() }}');

                fetch('{{ url_for("coaches.profile", id=coach.id) }}', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新头像显示
                        if (data.photo_url) {
                            if (avatarImage) {
                                avatarImage.src = data.photo_url + '?t=' + Date.now();
                            } else {
                                // 创建新的图片元素
                                const img = document.createElement('img');
                                img.src = data.photo_url + '?t=' + Date.now();
                                img.id = 'avatarImage';
                                img.alt = '{{ coach.real_name }}';

                                const avatarContainer = document.querySelector('.coach-avatar-large');
                                if (avatarPlaceholder) {
                                    avatarPlaceholder.remove();
                                }
                                avatarContainer.appendChild(img);
                            }
                        }

                        showMessage('头像更新成功！', 'success');
                    } else {
                        showMessage(data.error || '头像上传失败', 'error');
                    }
                })
                .catch(error => {
                    showMessage('网络错误，请重试', 'error');
                    console.error('Error:', error);
                });
            }
        });
    }
    {% endif %}

    // 实时数据刷新（仅统计数据）
    {% if statistics %}
    const refreshStats = function() {
        fetch(`/coaches/api/{{ coach.id }}/statistics`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const stats = data.data;

                    // 更新主要统计
                    const elements = {
                        '.performance-card.students .performance-number': stats.total_students,
                        '.performance-card.revenue .performance-number': stats.month_revenue,
                        '.performance-card.hours .performance-number': stats.total_hours,
                        '.performance-card.rating .performance-number': stats.avg_rating
                    };

                    Object.entries(elements).forEach(([selector, value]) => {
                        const element = document.querySelector(selector);
                        if (element) {
                            element.textContent = value;
                        }
                    });

                    // 更新迷你统计
                    const miniStats = document.querySelectorAll('.stat-mini-number');
                    if (miniStats.length >= 4) {
                        miniStats[0].textContent = stats.total_students;
                        miniStats[1].textContent = stats.total_hours;
                        miniStats[2].textContent = stats.month_revenue;
                        miniStats[3].textContent = stats.avg_rating;
                    }
                }
            })
            .catch(error => console.error('Error fetching stats:', error));
    };

    // 每60秒刷新一次统计数据
    setInterval(refreshStats, 60000);
    {% endif %}
});
</script>
{% endblock %}